<template>
  <div class="teacher-management">
    <el-card class="management-card">
      <template #header>
        <div class="card-header">
          <div>
            <h1>导师库管理</h1>
            <p>管理导师数据</p>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="openTeacherModal">
              <el-icon><Plus /></el-icon>
              添加新导师
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索导师名称、描述或ID..."
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 空数据提示 -->
      <div v-if="!loading && filteredTeachers.length === 0" class="empty-container">
        <el-empty description="暂无导师数据" />
        <el-button type="primary" size="small" class="mt-3" @click="openTeacherModal">
          立即添加
        </el-button>
      </div>

      <!-- 导师表格 -->
      <el-table
        v-else
        v-loading="loading"
        :data="filteredTeachers"
        style="width: 100%"
        stripe
        row-key="teacher_id" 
        size="default"
      >
        <el-table-column prop="teacher_id" label="ID" width="200"  /> 
        <el-table-column prop="name" label="名称" width="150" show-overflow-tooltip />
        <el-table-column prop="desc" label="描述" width="200" show-overflow-tooltip />
        <el-table-column prop="postport_url" label="海报URL" min-width="250" show-overflow-tooltip> 
          <template #default="{ row }">
            <el-link
              v-if="row.postport_url" 
              :href="row.postport_url" 
              target="_blank"
              type="primary"
              :underline="false"
            >
              {{ row.postport_url.length > 30 ? row.postport_url.slice(0, 30) + '...' : row.postport_url }} 
            </el-link>
            <span v-else class="text-gray">—</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" >
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="editTeacher(row)"
            >
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="confirmDelete(row)"
            >
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 导师模态框 -->
      <el-dialog
        v-model="teacherModalVisible"
        :title="teacherModalTitle"
        width="500px"
        @close="resetTeacherForm"
      >
        <el-form
          ref="teacherFormRef"
          :model="teacherForm"
          :rules="teacherFormRules"
          label-width="80px"
          @submit.prevent
        >
          <el-form-item label="名称" prop="name">
            <el-input
              v-model="teacherForm.name"
              placeholder="请输入导师名称"
              maxlength="30"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input
              v-model="teacherForm.desc"
              placeholder="请输入导师描述"
              maxlength="500"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="海报URL" prop="postport_url"> 
            <el-input
              v-model="teacherForm.postport_url" 
              placeholder="请输入有效URL"
              clearable
            />
            <div class="tip">支持跳转预览，建议使用 https</div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="teacherModalVisible = false">取消</el-button>
            <el-button type="primary" @click="saveTeacher" :loading="saving">
              {{ isEditing ? '更新导师' : '添加导师' }}
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 删除确认对话框 -->
      <el-dialog
        v-model="deleteDialogVisible"
        title="⚠️ 确认删除"
        width="400px"
        align-center
      >
        <p>确定要删除导师 <strong>{{ teacherToDelete?.name || '—' }}</strong> 吗？</p>
        <p class="delete-warning">此操作不可撤销，相关数据将被永久删除。</p>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteTeacher" :loading="deleting">
              删除
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Edit, Delete, Search } from '@element-plus/icons-vue'
import api from '@/api'

// ========== 状态 ==========
const loading = ref(false)
const saving = ref(false)
const deleting = ref(false)
const teacherModalVisible = ref(false)
const deleteDialogVisible = ref(false)
const searchQuery = ref('')
const teachers = ref([])
const teacherFormRef = ref(null)
const teacherToDelete = ref(null)

// ========== 表单数据 ========== ✅ 使用后端真实字段名
const teacherForm = reactive({
  teacher_id: '',   // ✅
  name: '',
  desc: '',
  postport_url: ''  // ✅
})

const isEditing = computed(() => !!teacherForm.teacher_id) // ✅
const teacherModalTitle = computed(() => isEditing.value ? '编辑导师' : '添加新导师')

// ========== 验证规则 ========== ✅ 字段名同步修改
const teacherFormRules = {
  name: [
    { required: true, message: '请输入导师名称', trigger: 'blur' },
    { max: 30, message: '名称不能超过30个字符', trigger: 'blur' }
  ],
  desc: [
    { required: true, message: '请输入导师描述', trigger: 'blur' },
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ],
  postport_url: [ // ✅
    { required: true, message: '请输入海报URL', trigger: 'blur' },

  ]
}

// ========== 计算属性 ========== ✅ 搜索字段同步修改
const filteredTeachers = computed(() => {
  const query = searchQuery.value.trim().toLowerCase()
  if (!query) return teachers.value

  return teachers.value.filter(teacher =>
    teacher.name?.toLowerCase().includes(query) ||
    teacher.desc?.toLowerCase().includes(query) ||
    String(teacher.teacher_id).includes(query) // ✅
  )
})

// ========== 方法 ==========
const fetchTeachers = async () => {
  loading.value = true
  try {
    const data = await api.getTeachersList()
    teachers.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('加载失败：' + (error.message || '请稍后重试'))
    teachers.value = []
  } finally {
    loading.value = false
  }
}

const openTeacherModal = () => {
  resetTeacherForm()
  teacherModalVisible.value = true
}

// ✅ 已正确使用后端字段名，无需修改
const editTeacher = (teacher) => {
  if (!teacher) return
  Object.assign(teacherForm, {
    teacher_id: teacher.teacher_id || '',
    name: teacher.name || '',
    desc: teacher.desc || '',
    postport_url: teacher.postport_url || ''
  })
  teacherModalVisible.value = true
}

// ✅ 已正确使用后端字段名，无需修改
const resetTeacherForm = () => {
  if (teacherFormRef.value) teacherFormRef.value.resetFields()
  Object.assign(teacherForm, {
    teacher_id: '',
    name: '',
    desc: '',
    postport_url: ''
  })
}

const saveTeacher = async () => {
  if (!teacherFormRef.value) return

  await teacherFormRef.value.validate(async (valid) => {
    if (!valid) return

    saving.value = true
    try {
      const payload = { ...teacherForm } // ✅ 字段名已匹配后端

      if (isEditing.value) {
        await api.updateTeacher(payload)
        ElMessage.success('✅ 导师信息更新成功')
      } else {
        await api.createTeacher(payload)
        ElMessage.success('✅ 新导师添加成功')
      }

      teacherModalVisible.value = false
      await fetchTeachers()
    } catch (error) {
      ElMessage.error('❌ 操作失败：' + (error.message || '请稍后重试'))
    } finally {
      saving.value = false
    }
  })
}

const confirmDelete = (teacher) => {
  if (!teacher) return
  teacherToDelete.value = { ...teacher }
  deleteDialogVisible.value = true
}

const deleteTeacher = async () => {
  if (!teacherToDelete.value?.teacher_id) return // ✅

  deleting.value = true
  try {
    await api.deleteTeacher({ teacher_id: teacherToDelete.value.teacher_id }) // ✅
    ElMessage.success('✅ 删除成功')
    deleteDialogVisible.value = false
    teacherToDelete.value = null
    await fetchTeachers()
  } catch (error) {
    ElMessage.error('❌ 删除失败：' + (error.message || '请稍后重试'))
  } finally {
    deleting.value = false
  }
}

const handleSearch = () => {
  // 由 computed 自动响应，无需额外逻辑
}

// ========== 生命周期 ==========
onMounted(() => {
  fetchTeachers()
})
</script>

<style scoped>
/* 样式部分无需修改，保持原样 */
.teacher-management {
  padding: 20px;
}

.management-card {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.card-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.card-header p {
  margin: 4px 0 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-bar {
  margin: 20px 0;
}

.empty-container {
  text-align: center;
  padding: 60px 20px;
}

.tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.delete-warning {
  color: var(--el-color-danger);
  font-size: 14px;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.text-gray {
  color: #909399;
}

:deep(.el-table .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:deep(.el-button.is-link) {
  padding: 0;
  min-width: auto;
}

.mt-3 {
  margin-top: 12px;
}
</style>